package sdk

import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	utilali "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"likeadmin/util"
)

var SMSAliyun = smsAliyun{}

type smsAliyun struct{}

func (s smsAliyun) initClient(AccessKey string, SecretKey string) (client *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: tea.String(AccessKey),
		// 必填，您的 AccessKey Secret
		AccessKeySecret: tea.String(SecretKey),
	}
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	client = &dysmsapi20170525.Client{}
	client, _err = dysmsapi20170525.NewClient(config)
	return client, _err
}

func (s smsAliyun) Send(templateId string, phone string, param string) (_err error) {

	engineConf := util.SettingUtil.GetSmsEngineConf("aliyun")

	client, _err := s.initClient(engineConf.AppKey, engineConf.SecretKey)
	if _err != nil {
		return _err
	}

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phone),
		SignName:      tea.String(engineConf.Sign),
		TemplateCode:  tea.String(templateId),
		TemplateParam: tea.String(param),
	}

	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		//result, _err := client.SendSmsWithOptions(sendSmsRequest, &utilali.RuntimeOptions{})
		_, _err = client.SendSmsWithOptions(sendSmsRequest, &utilali.RuntimeOptions{})
		if _err != nil {
			return _err
		}
		// 更改记录中的发送状态
		//	println(result.String())

		return nil
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 如有需要，请打印 error
		_, _err = utilali.AssertAsString(error.Message)
		if _err != nil {
			return _err
		}
	}

	return
}
